// import axios from 'axios'
export default {

  getMap(key) {
    if (!key) {
      return {}
    }
    if (Array.isArray(key)) {
      var list = key
    } else {
      list = this.getList(key)
    }

    if (!list) {
      return {}
    }
    var ret = {}
    var _item

    for (var i = 0, len = list.length; i < len; ++i) {
      _item = list[i]
      if (!_item) { continue }
      if (!_item.value) { continue }

      ret[_item.value] = _item.text
    }
    return ret
  },
  getList(key) {
    if (!key) {
      return []
    }
    // 如果缓存中有，直接返回
    var item = localStorage.getItem('dict')
    var result = []
    if (item !== null) {
      var list = JSON.parse(item)
      result = list[key] || []
    }
    if (result.length === 0) {
      let xhr = new XMLHttpRequest()
      xhr.open('GET', '/ect/wechat/static/dict.json', false)
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 & xhr.status === 200 || xhr.status === 304) {
          list = JSON.parse(xhr.responseText)
          localStorage.setItem('dict', JSON.stringify(list))
        }
      }
      xhr.send()
      result = list[key] || []
    }
    return result
  },
  getText(key, val) {
    if (!key) {
      return ''
    }
    if (!val) {
      return ''
    }
    var dictMap = this.getMap(key)
    if (dictMap) {
      var ret = dictMap[val]
      ret = ret || ''
      return ret
    } else {
      return ''
    }
  },
  getValue(key, text) {
    if (!key) {
      return ''
    }
    if (!text) {
      return ''
    }
    var dictList = this.getList(key)
    for (var i = 0, len = dictList.length; i < len; i++) {
      var item = dictList[i]
      if (text === item.text) {
        return item.value || ''
      }
    }
    return ''
  }
}
